package cn.xhjava.crm.workbench.controller;

import cn.xhjava.crm.commons.ReturnObject;
import cn.xhjava.crm.commons.SysContants;
import cn.xhjava.crm.commons.util.DateUtils;
import cn.xhjava.crm.commons.util.ExceptionUtil;
import cn.xhjava.crm.commons.util.UUIDUtils;
import cn.xhjava.crm.settings.domain.DicValue;
import cn.xhjava.crm.settings.domain.User;
import cn.xhjava.crm.settings.service.DicValueService;
import cn.xhjava.crm.settings.service.UserService;
import cn.xhjava.crm.workbench.domain.Contacts;
import cn.xhjava.crm.workbench.domain.Customer;
import cn.xhjava.crm.workbench.domain.CustomerRemark;
import cn.xhjava.crm.workbench.domain.Tran;
import cn.xhjava.crm.workbench.service.ContactsService;
import cn.xhjava.crm.workbench.service.CustomerRemarkService;
import cn.xhjava.crm.workbench.service.CustomerService;
import cn.xhjava.crm.workbench.service.TranService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:   XiaHu
 * Date:     2023/6/27
 * 客户
 */
@Controller
public class CustomerController {
    private static final Logger log = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private DicValueService dicValueService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private ContactsService contactsService;

    @Autowired
    private TranService tranService;

    @Autowired
    private CustomerRemarkService customerRemarkService;


    @RequestMapping("/workbench/customer/index")
    public String index(HttpServletRequest request) {
        log.info("跳转到 customer index");

        //调用service层方法，查询动态数据
        List<User> userList = null;
        try {
            userList = userService.queryAllUsers();
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //把数据保存到request中
        request.setAttribute("userList", userList);
        return "workbench/customer/index";
    }

    @RequestMapping("/workbench/customer/queryCustomerForPage")
    public @ResponseBody
    Object selectForPage(String name,
                         String owner,
                         String website,
                         String phone,
                         int pageNo, int pageSize, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("owner", owner);
        map.put("name", name);
        map.put("website", website);
        map.put("phone", phone);
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);
        map.put("userId", user.getId());
        //调用service层方法，查询数据
        List<Customer> customerList = null;
        int totalRows = 0;
        try {
            customerList = customerService.selectForPage(map);
            totalRows = customerService.selectCountForPage(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //根据查询结果结果，生成响应信息
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("customerList", customerList);
        retMap.put("totalRows", totalRows);
        return retMap;
    }


    @RequestMapping("/workbench/customer/add")
    public @ResponseBody
    Object add(Customer customer, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        customer.setId(UUIDUtils.getUUID());
        customer.setCreateTime(DateUtils.formateDateTime(new Date()));
        customer.setCreateBy(user.getId());
        customer.setOwner(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，保存创建的线索
            int ret = customerService.add(customer);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("添加成功");
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }

    // 查询
    @RequestMapping("/workbench/customer/queryCustomerById")
    public @ResponseBody
    Object selectById(String id) {
        //调用service层方法，查询市场活动
        Customer customer = null;
        try {
            customer = customerService.selectById(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        return customer;
    }

    // 修改
    @RequestMapping("/workbench/customer/update")
    public @ResponseBody
    Object update(Customer customer, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        customer.setEditTime(DateUtils.formateDateTime(new Date()));
        customer.setEditBy(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，修改联系人
            int ret = customerService.update(customer);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }

    // 删除
    @RequestMapping("/workbench/customer/delete")
    public @ResponseBody
    Object delete(String[] id) {
        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，删除市场活动
            int ret = customerService.delete(id);
            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }


    @RequestMapping("/workbench/customer/detail")
    public String detail(String id, HttpServletRequest request) {
        Customer customer = null;
        List<User> userList = null;
        List<DicValue> appellationList = null;
        List<DicValue> sourceList = null;
        List<CustomerRemark> remarkList = null;
        List<DicValue> stageList = null;
        List<DicValue> transactionTypeList = null;
        List<Contacts> contactsList = null;
        List<Tran> transactionList = null;
        try {
            customer = customerService.selectDetailById(id);
            userList = userService.queryAllUsers();
            appellationList = dicValueService.queryDicValueByTypeCode("appellation");
            sourceList = dicValueService.queryDicValueByTypeCode("source");
            remarkList = customerRemarkService.selectDetailById(id);
            stageList = dicValueService.queryDicValueByTypeCode("stage");
            transactionTypeList = dicValueService.queryDicValueByTypeCode("transactionType");
            contactsList = contactsService.selectContactsListByCustomerId(id);
            transactionList = tranService.selectTransactionListByCustomerId(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        request.setAttribute("userList", userList);
        request.setAttribute("stageList", stageList);
        request.setAttribute("transactionTypeList", transactionTypeList);
        request.setAttribute("remarkList", remarkList);
        request.setAttribute("appellationList", appellationList);
        request.setAttribute("transactionList", transactionList);
        request.setAttribute("sourceList", sourceList);
        request.setAttribute("customer", customer);
        request.setAttribute("contactsList", contactsList);
        //请求转发
        return "workbench/customer/detail";
    }
}
